package pl.bristleback.chat.actions;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.bristleback.chat.constants.UserState;
import pl.bristleback.chat.exceptions.UserExistsException;
import pl.bristleback.chat.services.UsersService;
import pl.bristleback.chat.utils.SendMessageSupport;
import pl.bristleback.chat.vo.User;
import pl.bristleback.server.bristle.actions.AnnotatedRemoteAction;
import pl.bristleback.server.bristle.actions.RemoteAction;
import pl.bristleback.server.bristle.binding.Bind;
import pl.bristleback.server.bristle.binding.ObjectBinder;
import pl.bristleback.server.bristle.binding.Property;
import pl.bristleback.server.bristle.exceptions.BindingException;
import pl.bristleback.server.bristle.rights.ConnectorRightsUtil;
import pl.bristleback.server.bristle.utils.BristleTokenFactory;
import pl.bristleback.server.bristle.utils.JsonUtil;

/**
 * //@todo class description
 * <p/>
 * Created on: 11.04.11 16:59 <br/>
 *
 * @author Paweł Machowski
 */
@Controller
@AnnotatedRemoteAction(actionName = "LOG_IN")
public class JoinChatAction implements RemoteAction {
  private static Logger log = Logger.getLogger(JoinChatAction.class.getName());


  @Autowired
  private SendMessageSupport sender;

  @Autowired
  private UsersService usersService;

  @Bind(properties = @Property(name = "name", required = true))
  private ObjectBinder<User> binder;

  @Override
  public void performAction(WebSocketConnector webSocketConnector, Token token) {


    try {
      User user = binder.bind(token);
      user.setId(webSocketConnector.getId());
      usersService.addUser(user);

      ConnectorRightsUtil.addRight(webSocketConnector, UserState.LOGGED.toString());

      Token sendToken = BristleTokenFactory.createJsonToken("listOfUsers", JsonUtil.getJsonArray(usersService.getAllUsers(), true), "users");
      sender.broadcastLogged(sendToken);

      Token newUserToken = BristleTokenFactory.createResponseToken(token);
      newUserToken.setString("username", user.getName());
      sender.broadcastLogged(newUserToken);

    } catch (JSONException e) {
      log.error(e);
    } catch (BindingException e) {
      log.error(e);
      Token error = BristleTokenFactory.createValidationExceptionToken(token, e.getBindingResult());
      sender.send(error, webSocketConnector);
    } catch (UserExistsException e) {
      Token userExist = BristleTokenFactory.createExceptionToken(token, "USER_EXIST_EXCEPTION");
      sender.send(userExist, webSocketConnector);
    }

  }
}